package com.c.ctgproject.wiget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.c.ctgproject.utils.MyLog
import com.c.ctgproject.utils.pickerimage.utils.ScreenUtil
import kotlinx.android.synthetic.main.activity_pre_production.view.*
import java.io.File
import java.io.FileOutputStream


/**
 * 作者:LiBW
 * 创建日期: 2021/7/6
 * 描述:档案部 签名
 */
class SignatureView(context: Context, attributes: AttributeSet?) : View(context, attributes) {
    //画笔
    private val mPaint = Paint()

    //路径
    private var mPath = Path()
    var bitmap: Bitmap? = null
    var mCanvas: Canvas? = null

    init {
        bitmap = Bitmap.createBitmap(1080, 1080, Bitmap.Config.ARGB_8888)
        bitmap?.eraseColor(Color.WHITE)
        mCanvas = Canvas(bitmap!!)
        mPaint.isAntiAlias = true
        mPaint.isDither = true
        mPaint.color = Color.BLACK
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = 12f
        mPaint.strokeCap = Paint.Cap.ROUND
        mPaint.strokeJoin = Paint.Join.ROUND
        //创建路径
        mPath = Path()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawPath(mPath, mPaint)
        mCanvas?.drawPath(mPath, mPaint)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                mPath.moveTo(x, y)
            }
            MotionEvent.ACTION_MOVE -> {
                mPath.lineTo(x, y)
            }
            MotionEvent.ACTION_UP -> {

            }
        }
        invalidate()
        return true
    }

    /**重置签名*/
    fun initPaint() {
        mPath = Path()
        bitmap = Bitmap.createBitmap(1080, 1080, Bitmap.Config.ARGB_8888)
        bitmap?.eraseColor(Color.WHITE)
        mCanvas = Canvas(bitmap!!)
        invalidate()
    }

    /**将签名保存为图片*/
    fun saveImage(): String {
//        val bitmap = Bitmap.createBitmap(700, 700, Bitmap.Config.ARGB_8888)
//        bitmap.eraseColor(Color.WHITE)
        val savePath = context.getExternalFilesDir(null)?.absolutePath + "file_signature.jpg"
        return try {
           val back= bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(File(savePath)))
            if (back==true){
                savePath
            }else{
                "0"
            }
        } catch (e: Exception) {
            "0"
        }
    }
}